package com.lv.common.widget.video_editor

import android.content.Context
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

/**
 * 作者： ygx
 * 创建日期：2024/3/8 5:16 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：
 */
/**
 * 监听recycleView滑动状态，
 * 自动播放可见区域内的第一个视频
 */
public class AutoPlayScrollListener(
    private val context: Context,
    private var onAutoPlayVideoListener: AutoPlayVideo?
) :
    RecyclerView.OnScrollListener() {
    private var firstVisibleItem = 0
    private var lastVisibleItem = 0
    private var visibleCount = 0
    private var thisPosition = -1

    /**
     * 被处理的视频状态标签
     */
    enum class VideoTagEnum {
        /**
         * 自动播放视频
         */
        TAG_AUTO_PLAY_VIDEO,

        /**
         * 暂停视频
         */
        TAG_PAUSE_VIDEO
    }

    override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
        super.onScrollStateChanged(recyclerView, newState)
        when (newState) {
            RecyclerView.SCROLL_STATE_IDLE ->
                onAutoPlayVideoListener?.playVideo(
                    recyclerView,
                    firstVisibleItem,lastVisibleItem,
                    VideoTagEnum.TAG_AUTO_PLAY_VIDEO
                )
            RecyclerView.SCROLL_STATE_DRAGGING, RecyclerView.SCROLL_STATE_SETTLING -> {}
            else -> {}
        }
    }


    interface AutoPlayVideo {

        fun playVideo(recyclerView: RecyclerView?, firstVisibleItem: Int, lastVisibleItem: Int, handleVideoTag: VideoTagEnum)
    }

    override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
        super.onScrolled(recyclerView, dx, dy)
        val layoutManager = recyclerView.layoutManager
        if (layoutManager is LinearLayoutManager) {
            val linearManager = layoutManager
            firstVisibleItem = linearManager.findFirstVisibleItemPosition()
            lastVisibleItem = linearManager.findLastVisibleItemPosition()
            val eddVisibleItem: Int = layoutManager.findLastCompletelyVisibleItemPosition()

            if (eddVisibleItem == thisPosition) {
                return
            } else {
                thisPosition = eddVisibleItem
            }
//            val thisVideoView = eddVisibleItem - firstVisibleItem

            visibleCount = lastVisibleItem - firstVisibleItem
        }
    }

}